import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '../stores/user'
import { checkRoutePermission } from '../utils/permission'
import UniversalLayout from '../layouts/UniversalLayout.vue'
import { ElMessage } from 'element-plus'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    // 重定向根路径到仪表板
    {
      path: '/',
      redirect: '/dashboard'
    },
    
    // 统一布局的页面
    {
      path: '/dashboard',
      component: UniversalLayout,
      children: [
        {
          path: '',
          name: 'dashboard',
          component: () => import('../views/Home.vue'),
          meta: { 
            requiresAuth: true,
            roles: ['admin', 'user'],
            title: '个人仪表板'
          }
        }
      ]
    },
    
    // 个人中心相关
    {
      path: '/profile',
      component: UniversalLayout,
      children: [
        {
          path: '',
          name: 'profile',
          component: () => import('../views/Profile.vue'),
          meta: { 
            requiresAuth: true,
            roles: ['admin', 'user'],
            title: '个人资料'
          }
        },
        {
          path: 'edit',
          name: 'profile-edit',
          component: () => import('../views/ProfileEdit.vue'),
          meta: { 
            requiresAuth: true,
            roles: ['admin', 'user'],
            title: '编辑资料'
          }
        }
      ]
    },
    
    // 管理员功能
    {
      path: '/admin',
      component: UniversalLayout,
      meta: { 
        requiresAuth: true,
        roles: ['admin']
      },
      children: [
        {
          path: 'dashboard',
          name: 'admin-dashboard',
          component: () => import('../views/admin/AdminDashboard.vue'),
          meta: { 
            requiresAuth: true,
            roles: ['admin'],
            title: '数据概览'
          }
        },
        {
          path: 'users',
          name: 'admin-users',
          component: () => import('../views/admin/UserManagement.vue'),
          meta: { 
            requiresAuth: true,
            roles: ['admin'],
            title: '用户管理'
          }
        }
      ]
    },
    
    // 无需布局的页面
    {
      path: '/login',
      name: 'login',
      component: () => import('../views/Login.vue'),
      meta: { requiresAuth: false }
    },
    {
      path: '/register',
      name: 'register',
      component: () => import('../views/Register.vue'),
      meta: { requiresAuth: false }
    },
    
    // 错误页面
    {
      path: '/403',
      name: 'forbidden',
      component: () => import('../views/Forbidden.vue'),
      meta: { requiresAuth: false }
    },
    {
      path: '/:pathMatch(.*)*',
      name: 'not-found',
      component: () => import('../views/NotFound.vue'),
      meta: { requiresAuth: false }
    }
  ]
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
  const userStore = useUserStore()
  
  console.log('路由守卫检查:', { 
    to: to.path, 
    isLoggedIn: userStore.isLoggedIn, 
    hasToken: !!userStore.token,
    userRole: userStore.currentUser?.userRole
  })
  
  // 如果路由需要认证
  if (to.meta.requiresAuth) {
    // 检查是否已登录
    if (!userStore.isLoggedIn) {
      // 尝试获取用户信息（如果有token的话）
      const user = await userStore.getCurrentUser()
      if (!user) {
        // 未登录，跳转到登录页
        console.log('未登录，跳转到登录页')
        next('/login')
        return
      }
    }
    
    // 检查权限
    if (!checkRoutePermission(to)) {
      console.log('权限不足，跳转到403页面')
      ElMessage.error('您没有权限访问该页面')
      next('/403')
      return
    }
  }
  
  // 如果已登录且访问登录/注册页，跳转到仪表板
  if (userStore.isLoggedIn && (to.path === '/login' || to.path === '/register')) {
    console.log('已登录，跳转到仪表板')
    next('/dashboard')
    return
  }
  
  next()
})

export default router
